package com.devunion.bogdan.spring;

import org.apache.commons.lang.StringUtils;

import org.apache.log4j.Logger;

import java.io.File;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;


/**
 * Utility class to work with files.
 */
public class FileUtil {
    private static Logger log = Logger.getLogger(FileUtil.class);

    public static File[] fileFilter(File[] flist, String mask) {
        if (flist == null) {
            log.debug("FILE LIST CAN'T BE NULL");
            throw new IllegalArgumentException("FILE LIST CAN'T BE NULL");
        }
        if (mask == null) {
            log.debug("MASK CAN'T BE NULL");
            throw new IllegalArgumentException("MASK CAN'T BE NULL");
        }
        if ("".equals(mask)) {
            return flist;
        }

        List<File> files = new ArrayList<File>();

        // replace  ? = [^?] ; * = [^?]*   for Pattern.matches;
        mask = mask.replaceAll("\\*", "[^?]*").replaceAll("\\?", "[^?]");
        String[] masks = StringUtils.split(mask, ",");
        for (String fileMask : masks) {
            for (File file : flist) {
                if (Pattern.matches(fileMask.trim().toLowerCase(),
                            file.getName().toLowerCase())) {
                    files.add(file);
                }
            }
        }

        return files.toArray(new File[files.size()]);
    }
}
